// pages/pk/pk.js
import {getNavSize, getSystemSize} from "../../utils/system"
import {ANSWERTYPE} from "../../core/enum"
import {Pk} from "../../model/pk"
import {User} from "../../model/user"
import {Score} from "../../model/score"
Page({
    data: {
	    current: 0,
	    answerIndex: Number,
	    swiperHeight: Number,
	    isChoose: false,
	    rightCount: 0,
	    wrongCount: 0,
	    countStatus: false,
	    totalTime: 0,
	    startMaskShow: false,
		doneMaskShow: false,
	    isWrongAnswer: false,
	    timer: 3,
	    rightRate: 0,
	    rightAnswerIndex: Number,
	    countDownTime: 0,
		pk: null
    },
	hasShare: false,
	pkid: null,
	source: null,
	_countDownTime: 0,
	interval: null,
	onLoad: async function (options) {
    	const res = await getSystemSize()
		const res1 = await getNavSize()
	    const windowHeight = res.windowHeight
		const navigationHeight = res1.navigationHeight
		const statusBarHeight = res1.statusBarHeight
		const swiperHeight = windowHeight - navigationHeight - statusBarHeight
		this.setData({
			swiperHeight: swiperHeight
		})
		this.pkid = options.pkid
		this.source = options.source
		this.loadPkDetail(this.pkid)
    },
	async loadPkDetail(pkid) {
		const pk = await Pk.getPkDetail(pkid)
		const user = new User()
		console.log(pk)
		if (this.source === 'right') {
			if (pk.right) {
				if (!pk.winner) {
					if (user.user.id!==pk.right.id) {
						wx.redirectTo({
							url: `/pages/pkDetail/pkDetail?pkid=${this.pkid}&source=share`
						})
					}
				}else {
					wx.redirectTo({
						url: `/pages/pkDetail/pkDetail?pkid=${this.pkid}&source=share`
					})
				}
			}else {
				if (user.user.id === pk.left.id) {
					wx.redirectTo({
						url: `/pages/pkDetail/pkDetail?pkid=${this.pkid}&source=share`
					})
				}else {
					if (pk.right) {
						wx.redirectTo({
							url: `/pages/pkDetail/pkDetail?pkid=${this.pkid}&source=share`
						})
					}else {
						await Pk.joinPkRight(this.pkid)
					}
				}
			}
		}
		this.setData({
			pk,
			startMaskShow: true
		})
	},
	async updateLeftPkDetail() {
		await Pk.updateLeftPkDetail(this.pkid, {
			left_duration: this._countDownTime,
			left_count: this.data.rightCount,
			left_score: this.data.rightCount
		})
		await Score.uploadPoint({
			point: this.data.rightCount,
			pk_id: this.pkid
		})
	},
	async updateRightDetail() {
		await Pk.updateRightPkDetail(this.pkid, {
			right_duration:this._countDownTime,
			right_count: this.data.rightCount,
			right_score: this.data.rightCount
		})
		await Score.uploadPoint({
			point: this.data.rightCount,
			pk_id: this.pkid
		})
	},
	/**
	 * 计算倒计时时间
	 * */
	onCalcCountTime(option) {
		const countDownTime = option.detail.countDownTime
		this._countDownTime += 1
		if (countDownTime === 30) {
			this._countDownTime += 1
			this.calcWrongAnswer(this.data.current, this.data.wrongCount)

			const topic = this.data.pk.linked_questions[this.data.current]
			let index
			topic.question.answers.forEach((item, innerIndex) => {
				if (item.is_answer === false) {
					index = innerIndex
				}
			})
			this.setData({
				countStatus: false,
				rightAnswerIndex: this.getRightAnswerIndex(this.data.current),
				answerIndex: index,
			})
		}
	},

	async calcRightRateAndTime() {
		let integerNum = parseInt(this._countDownTime / 60)
		let decimalNum = this._countDownTime % 60
		integerNum = integerNum.toString().length === 1 ? `0${integerNum}` : integerNum
		decimalNum = decimalNum.toString().length === 2 ? decimalNum : `0${decimalNum}`

		this.setData({
			countDownTime: `${integerNum}:${decimalNum}`
		})

		if (this.data.rightCount === 0) {
			this.setData({
				rightRate: 0
			})
			return
		}
		let rate = (100 * (this.data.rightCount / this.data.pk.linked_questions.length)).toFixed(1)
		this.setData({
			rightRate: `${rate}%`,
		})
		if (this.source === 'left') {
			await this.updateLeftPkDetail()
			this.setData({
				doneMaskShow: true
			})
		} else {
			await this.updateRightDetail()
			wx.redirectTo({
				url: `/pages/pkDetail/pkDetail?pkid=${this.pkid}&source=share`
			})
		}
	},

	getRightAnswerIndex(current) {
		const topic = this.data.pk.linked_questions[current]
		let index
		topic.question.answers.forEach((item, innerIndex) => {
			if (item.is_answer === true) {
				index = innerIndex
			}
		})
		return index
	},
	onChoose(event) {
    	if (this.data.isChoose === true) {
    		return
	    }
		const rightAnswerIndex = this.getRightAnswerIndex(this.data.current)
		const chooseitem = event.currentTarget.dataset.chooseitem
		this.setData({
			countStatus: false,
			answerIndex: event.currentTarget.dataset.index,
			rightAnswerIndex: rightAnswerIndex
		})

		if (chooseitem.is_answer) {
			this.calcRightAnswer(this.data.current, this.data.rightCount)
		} else {
			this.calcWrongAnswer(this.data.current, this.data.wrongCount)
		}
	},

	/**
	 * 处理错误答案
	 * */
	calcWrongAnswer(current, wrongCount) {
		this.setData({
			wrongCount: (wrongCount + 1),
			isWrongAnswer: true,
			isChoose: true,
		})

		if (current + 1 === this.data.pk.linked_questions.length) {
			clearInterval(this.interval)
			this.calcRightRateAndTime()
			return
		}

		this.interval = setInterval(() => {
			let timer = this.data.timer
			this.setData({
				timer: timer - 1
			})
			if (this.data.timer === 0) {
				this.refreshData(current + 1)
				clearInterval(this.interval)
			}
		}, 1000)

	},

	/**
	 * 处理正确答案
	 * */
	calcRightAnswer(current, rightCount) {
		if ((current + 1) === this.data.pk.linked_questions.length) {
			this.setData({
				isChoose: true,
				rightCount: rightCount + 1,
			})
			if (current + 1 === this.data.pk.linked_questions.length) {
				clearInterval(this.interval)
				this.calcRightRateAndTime()
				return
			}

			this.interval = setInterval(() => {
				let timer = this.data.timer
				this.setData({
					timer: timer - 1
				})
				if (this.data.timer === 0) {
					this.refreshData(current + 1)
					clearInterval(this.interval)
				}
			}, 1000)
			return
		}
		this.setData({
			countStatus: true,
			rightCount: rightCount + 1,
			current: current + 1,
			isChoose: false
		})
	},

	catchTouchMove(res) {
    	return false;
	},

	onNext(event) {
		const index = event.currentTarget.dataset.index
		clearInterval(this.interval)
		this.refreshData(index + 1)
    },

	refreshData(index) {
		this.setData({
			isWrongAnswer: false,
			current: index,
			isChoose: false,
			countStatus: true,
			timer: 3
		})
	},

	onCloseMask() {
    	this.setData({
		    countStatus: true,
		    startMaskShow: false
	    })
	},

	async onAgainTap() {
		if (!this.hasShare) {
			await Pk.destoryPk(this.pkid)
		}
		wx.navigateBack()
	},
	onShareAppMessage() {
		this.hasShare = true
		return {
			title: '我已经完成了答题,快来和我PK吧！',
			path: `/pages/pk/pk?pkid=${this.pkid}&source=right`,
			imageUrl: 'https://kt-public.tempot.com/poems/covers/share-image.jpeg'
		}
	},
	async destroyPk() {
		await Pk.destoryPk(this.pkid)
	},
	onUnload() {
		this.setData({
			countStatus: false
		})
	}
})
